﻿using System;
using System.Data;
using System.Text;
using System.Drawing;
using System.Globalization;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.ComponentModel;
using System.Collections.Generic;
using WeifenLuo.WinFormsUI.Base;

namespace HRM
{
    public partial class FormSalaryPeriod : FormBaseDataGrid
    {
        private Ctrl_General mCtrlGeneral;
        private DataSet mdsSalPeriod;
        private SqlDataAdapter mdaSalPeriodUpdate;

        public FormSalaryPeriod()
        {
            InitializeComponent();
        }

        protected override void BasicForm_Load(object sender, EventArgs e)
        {
            base.BasicForm_Load(sender, e);
        }

        protected override void BaseForm_Activated(object sender, System.EventArgs e)
        {
            base.BaseForm_Activated(sender, e);
        }

        protected override void BaseForm_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            base.BaseForm_KeyDown(sender, e);
        }

        protected override void BasicForm_Closing(object sender, System.Windows.Forms.FormClosingEventArgs e)
        {
            base.BasicForm_Closing(sender, e);
        }

        #region Override LoadMasterData
        protected override void LoadMasterData()
        {
            try
            {
                btnCancel = btncancel;
                btnOk = btnok;
                lblStatus = lblstatus;
                LoadData();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Cannot load Salary Period Form'. Error: '" + ex.Message + "'", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }
        #endregion

        #region LoadData method
        private void LoadData()
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                if (mCtrlGeneral == null) mCtrlGeneral = new Ctrl_General();

                string ls_SQL = "Select Name, New_Fiscal_year, Closed, Date_Locked, Starting_Date, "
                    + "CreatedUser, UpdatedUser, CreatedDate, UpdatedDate, ID "
                    + "From HRM_Period Order By Starting_Date ";

                mdsSalPeriod = mCtrlGeneral.GetSelect(ls_SQL, "HRM_Period");
                mCtrlGeneral.GetAllData(out mdaSalPeriodUpdate, "HRM_Period", " Order By Starting_Date ");

                if (mdsSalPeriod == null) return;
                mdbg_dataGrid.DataSource = mdsSalPeriod;
                mdbg_dataGrid.DataMember = "HRM_Period";


                mRowManager = (CurrencyManager)mdbg_dataGrid.BindingContext[mdsSalPeriod, "HRM_Period"];
                // How to refresh the status of the row position?Ordinal_Number
                mRowManager.PositionChanged += new EventHandler(RowMaster_Changed);

                base.LoadMasterData();
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Salary Period Form'. Error: '" + ex.Message + "'", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Ctrl_LOG.Print("Salary Period Form", "LoadData() method", "Error: " + ex.Message);
                Cursor = Cursors.Default;
            }
        }
        #endregion

        public override void add()
        {
            base.add();
            btnCreateFiscalYear.Enabled = true;
        }

        public override void modify()
        {
            base.modify();
            btnCloseYear.Enabled = true;
        }

        public override void save()
        {
            try
            {
                if (mdsSalPeriod == null) return;
                mRowManager.EndCurrentEdit();
                if (!mdsSalPeriod.HasChanges())
                {
                    base.save();
                    return;
                }
                DataSet ldsHasChanged = mdsSalPeriod.GetChanges();
                foreach (DataRow dr in ldsHasChanged.Tables[0].Rows)
                {
                    if (dr.RowState == DataRowState.Deleted) continue;
                    if (dr.RowState == DataRowState.Added)
                    {
                        dr["CreatedDate"] = DateTime.Now;
                        dr["CreatedUser"] = mMainForm.ms_UserID;
                    }
                    else if (dr.RowState == DataRowState.Modified)
                    {
                        dr["UpdatedDate"] = DateTime.Now;
                        dr["UpdatedUser"] = mMainForm.ms_UserID;
                    }
                }
                string ls_ColName = "", ls_TableName = "";
                string ls_Error = mCtrlGeneral.Update(mdaSalPeriodUpdate, ldsHasChanged, "HRM_Period", out ls_ColName, out ls_TableName);
                if (ls_Error == "")
                {
                    mdsSalPeriod.AcceptChanges();
                    int li_pos = 0;
                    if (GetCurrentAction() == MODES.MODIFY) li_pos = mRowManager.Position;
                    LoadData();
                    if (li_pos > 0) mRowManager.Position = li_pos;
                    base.save();
                    btnCreateFiscalYear.Enabled = false;
                    btnCloseYear.Enabled = false;
                }
                else
                {
                    MessageBox.Show("Cannot save'. Error: '" + ls_Error + "'", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("DB Error: " + ex.Message, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public override void delete()
        {
            base.delete();
            if (!mb_AcceptDelete) return;
            DataSet ldsDelete = (DataSet)mdbg_dataGrid.DataSource;
            DataRow ldrDelete = ldsDelete.Tables[0].Rows[mRowManager.Position];
            ldrDelete.Delete();
            string lsColName = "", lsTableName = "";
            string lsReturnMessage = mCtrlGeneral.Update(mdaSalPeriodUpdate, ldsDelete, "HRM_Period", out lsColName, out lsTableName);
            if (lsReturnMessage != "")
            {
                MessageBox.Show("Cannot delete'. Error: '" + lsReturnMessage + "'", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                ldsDelete.RejectChanges();
                ldsDelete.AcceptChanges();
            }
        }

        public override void cancel()
        {
            btnCreateFiscalYear.Enabled = false;
            btnCloseYear.Enabled = false;
            if (mdsSalPeriod == null) return;
            mdsSalPeriod.RejectChanges();
            base.cancel();
        }

        private void SetDateLock(int ai_From, int ai_To)
        {
            ai_From--;
            for (int li_Row = ai_From; li_Row <= ai_To; li_Row++)
            {
                if (li_Row < ai_To) mdbg_dataGrid["Closed", li_Row].Value = true;
                mdbg_dataGrid["Date_Locked", li_Row].Value = true;
            }
        }

        private string GetMaxDateLocked()
        {	// Get max date locked
            string ls_SQL = "SELECT MAX(Starting_Date) FROM HRM_PERIOD WHERE Date_Locked = true ";
            string ls_MaxDate = mCtrlGeneral.GetSingleValue(ls_SQL);
            return ls_MaxDate;
        }

        private string GetMaxStartingDate()
        {
            // Get starting date default
            string ls_StartDate = "";
            if (mdsSalPeriod.Tables[0].Rows.Count > 0)
            {
                DataRow dr = mdsSalPeriod.Tables[0].Rows[mdsSalPeriod.Tables[0].Rows.Count - 1];
                ls_StartDate = ((DateTime)dr["Starting_Date"]).ToShortDateString();
            }
            if (ls_StartDate == null || ls_StartDate == "")
                ls_StartDate = DateTime.Now.ToString();
            else
                ls_StartDate = Convert.ToDateTime(ls_StartDate).AddMonths(1).ToString();
            return ls_StartDate;
        }

        private void btnCreateFiscalYear_Click(object sender, EventArgs e)
        {
            FormCreatePeriodSalYear lfrm_CreateFiscalYear = new FormCreatePeriodSalYear();
            CreateFiscalYearParam lstr_Param = new CreateFiscalYearParam();

            lstr_Param.ms_StartDate = GetMaxStartingDate();
            lstr_Param.ms_MaxDateLocked = GetMaxDateLocked();
            lfrm_CreateFiscalYear.SetParam(lstr_Param);
            if (lfrm_CreateFiscalYear.ShowDialog() == DialogResult.OK)
            {
                string ls_StartDate;
                int li_NMonths = Convert.ToInt16(lfrm_CreateFiscalYear.GetParam().ms_NumberMonths);
                int li_AddMonths = 0;
                if (li_NMonths < 1) return;
                for (int li_row = 1; li_row <= li_NMonths; li_row++)
                {
                    DataRow ldrPeriod = mdsSalPeriod.Tables[0].NewRow();
                    if (ldrPeriod != null)
                    {
                        ldrPeriod["Closed"] = false;
                        ldrPeriod["Date_Locked"] = false;
                        if (li_row == li_NMonths)
                            ldrPeriod["New_Fiscal_Year"] = true;
                        else
                            ldrPeriod["New_Fiscal_Year"] = 0;
                        ls_StartDate = Convert.ToDateTime(lfrm_CreateFiscalYear.GetParam().ms_StartDate).AddMonths(li_AddMonths).ToShortDateString();
                        DateTimeFormatInfo culture = new CultureInfo("en-US", true).DateTimeFormat;
                        DateTime ldt_StartDate = Convert.ToDateTime(ls_StartDate, culture);

                        li_AddMonths++;
                        ldrPeriod["Starting_Date"] = Convert.ToDateTime(ls_StartDate);
                        ldrPeriod["Name"] = Convert.ToDateTime(ls_StartDate).ToString("MMMM");//  GetMonthName(Convert.ToDateTime(ls_StartDate).  );
                        mdsSalPeriod.Tables[0].Rows.Add(ldrPeriod);
                    }
                    btnCreateFiscalYear.Enabled = false;
                }
                //mdbg_dataGrid.RefreshRow();
            }
        }

        private void btnCloseYear_Click(object sender, EventArgs e)
        {
            if (mdsSalPeriod.Tables[0].Rows.Count <= 0) return;
            bool lb_NewFiscalYear = false;
            DataRow dr = mdsSalPeriod.Tables[0].Rows[0];
            // if not specify new year --> do nothing
            if (!(bool)dr["New_Fiscal_Year"])
                MessageBox.Show("New Salary year must be created before closing the old year.", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            else
            {
                int li_begin;
                // get begin fiscal year
                for (li_begin = 1; li_begin < mdsSalPeriod.Tables[0].Rows.Count; li_begin++)
                {
                    DataRow drr = mdsSalPeriod.Tables[0].Rows[li_begin];
                    if (!(bool)drr["Closed"])
                    {
                        lb_NewFiscalYear = true;
                        break;
                    }
                }

                if (lb_NewFiscalYear) // if have new salary year --> get end salary year
                {
                    lb_NewFiscalYear = false;
                    int li_end;
                    // get end salary year
                    for (li_end = li_begin; li_end < mdsSalPeriod.Tables[0].Rows.Count; li_end++)
                    {
                        DataRow drrr = mdsSalPeriod.Tables[0].Rows[li_end];
                        if (((bool)drrr["New_Fiscal_Year"]) && (!(bool)drrr["Date_Locked"]))
                        {
                            lb_NewFiscalYear = true;
                            break;
                        }
                    }
                    if (lb_NewFiscalYear)
                    {	// set closed
                        string[] lsa_param = new string[2];
                        DataRow ddr = mdsSalPeriod.Tables[0].Rows[li_begin];
                        lsa_param[0] = ((DateTime)ddr["Starting_Date"]).ToShortDateString();
                        ddr = mdsSalPeriod.Tables[0].Rows[li_end];
                        lsa_param[1] = ((DateTime)ddr["Starting_Date"]).ToShortDateString();
                        DialogResult ldlg_Msg = MessageBox.Show("Do you realy wish to close the salary year from " + lsa_param[0] + " to " + lsa_param[1] + " ?", ConstantKeys.Title, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
                        if (ldlg_Msg == DialogResult.Yes)
                        {
                            SetDateLock(li_begin, li_end);
                        }
                    }
                    else
                    {	// báo lỗi --> xác định năm mới.
                        MessageBox.Show("The new year must be specified.", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }
                }
                else
                {	// báo lỗi --> chưa tạo năm mới.
                    MessageBox.Show("The new year has not created yet.", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
        }

        private void btnok_Click(object sender, System.EventArgs e)
        {
            save();
        }

        private void btncancel_Click(object sender, System.EventArgs e)
        {
            cancel();
        }
        
    }
}
